# Description:
#   Allows Hubot to restart the DP in ECE.
#
# Commands:
#   hubot restart Node_IP DP_Name
#   hubot check Node_IP DP_Name
#

module.exports = (robot) ->
  robot.respond /(?:restart) (.*) (.*)/i, (msg) ->
    restart msg

  robot.respond /(?:check) (.*) (.*)/i, (msg) ->
    check msg

# node.js deps
fs = require 'fs'
process = require 'child_process'

# app deps
yaml = require 'js-yaml'
yamlconfig = fs.readFileSync './scripts/eceConfig.yaml' , 'utf8'
config = yaml.load yamlconfig

restart = (msg) ->
  param =
    nodeId: new Buffer msg.match[1]
    dpName: new Buffer msg.match[2]

  try
    runCmd msg, param, "Restart DP", "restart"
  catch
    console.log "Got error: ", error

check = (msg) ->
  param =
    nodeId: new Buffer msg.match[1]
    dpName: new Buffer msg.match[2]

  try
    runCmd msg, param, "Check DP", "status"
  catch
    console.log "Got error: ", error


runCmd = (msg, param, cmdName, cmdValue) ->
  result = process.execFileSync(__dirname + "/" + config.eceDpCtrl, [param.nodeId, config.user, param.dpName, cmdValue])
  msg.send "#{cmdName} (#{param.dpName}) result is: #{result}"

